<?php
require_once(RX_PATH."Database/RXDatabaseConnection.php");

class DatabaseManager{
	
	private $connection;
	private $error;
	
	public function __construct(){
		$this->connect();
	}
	
	public function connect(){
		$this->connection = new RXDatabaseConnection();
		$this->connection->connect();
	}
	
	public function getWriter($object){		
		if(is_a($object, "Fetch")){
			require_once(DATABASE_WRITERS_PATH."FetchWriter.php");
			return new FetchWriter($object, $this->connection);
		}elseif(is_a($object, "Verb")){
			require_once(DATABASE_WRITERS_PATH."VerbWriter.php");
			return new VerbWriter($object, $this->connection);
		}elseif(is_a($object, "VerbConjugation")){
			require_once(DATABASE_WRITERS_PATH."VerbConjugationWriter.php");
			return new VerbConjugationWriter($object, $this->connection);
		}
		else{
			require_once(DATABASE_WRITERS_PATH."GenericWriter.php");
			return new GenericWriter();
		}
	}
	
	public function getReader($object){
		if(is_a($object, "Fetch")){
			require_once(DATABASE_READERS_PATH."FetchReader.php");
			return new FetchReader($object, $this->connection);
		}elseif(is_a($object, "Verb")){
			require_once(DATABASE_READERS_PATH."VerbReader.php");
			return new VerbReader($object, $this->connection);
		}elseif(is_a($object, "VerbConjugation")){
			require_once(DATABASE_READERS_PATH."VerbConjugationReader.php");
			return new VerbConjugationReader($object, $this->connection);
		}
		else{
			require_once(DATABASE_READERS_PATH."GenericReader.php");
			return new GenericReader();
		}
	}
	
	public function read($object, $operation = NULL){
		$reader = $this->getReader($object);
		$reader->setOperation($operation);
		return $reader;
	}
	
	public function save($object){
		$writer = $this->getWriter($object);
		$ret = $writer->save();
		if($ret){
			return $ret;
		}else{
			$this->error = $writer->getError();
			return FALSE;
		}
	}
	
	public function delete($object){		
		$writer = $this->getWriter($object);
		return $writer->delete();
	}
	
	public function update($object, $operation = NULL){
		$writer = $this->getWriter($object);
		$writer->setOperation($operation);
		return $writer->update();
	}
	
	public function getError(){
		if($this->error === FALSE)
			return "The Object sent is not defined in the Database Manager";
		return $this->error;
	}
}